<template>
  <div>
    <el-form :model="form" label-width="80px">
      <el-form-item label="标题">
        <el-input v-model="form.title"></el-input>
      </el-form-item>

      <el-form-item label="列表 ">
        <el-checkbox-group v-model="form.categories">
          <el-checkbox :label="item.id" v-for="(item,index) in fenlei" :key="index">{{item.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>



      <el-form-item label="文本">
        <!-- useCustomImageHandler一个布尔值 flase或者true
          image-added 调用一个函数进行图片的上传
           v-model="form.contenr" 绑定一个监控 然后把这个数据上传过去 里面添加H1 样式
          editorToolbar 配置项
        -->
        <VueEditor
          :useCustomImageHandler="true"
          @image-added="imgUpload"
          v-model="form.content"
          :editorToolbar="customToolbar"
        ></VueEditor>
      </el-form-item>

      <el-form-item label="缩略图">
          <!-- 照片墙 -->
      <el-upload
        :file-list="form.cover"
        :action="$axios.defaults.baseURL+'/upload'"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :headers="{Authorization:tokenss}"
        :on-success="Success"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt />
      </el-dialog>
      </el-form-item>


  <el-form-item label="类型">
            <el-radio-group v-model="form.type">
                <el-radio :label="1">文章</el-radio>
                <el-radio :label="2">视频</el-radio>
            </el-radio-group>
        </el-form-item>

  <!-- 提交 -->
       <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
        </el-form-item>


    </el-form>
  </div>
</template>

<script>
import { VueEditor } from "vue2-editor";
export default {
  components: {
    VueEditor
  },
  data() {

    return {
        postId : this.$route.query.id,

       tokenss:localStorage.getItem('token'),
      form: {
        categories: [],

        content: "<h1>没有内容</h1>",
        cover:[],
        type:1
      },
      fenlei: [],
      customToolbar: [
        ["bold", "italic", "underline"],
        [{ list: "ordered" }, { list: "bullet" }],
        ["image", "code-block"]
      ],
      dialogImageUrl: '',
      dialogVisible: false
    };
  },
  mounted() {
    // 发送AJAX请求 把获取到的数据渲染在页面上
    // 列表选项
    this.$axios({
      url: "/category",
      method: "get"
    }).then(res => {
      const { data } = res.data;
      // console.log(data);
      const NEWfenlei = [];
      data.forEach(element => {
        if (element.id != 999 && element.id != 0) {
          NEWfenlei.push(element);
        }
      });
      this.fenlei = NEWfenlei;
    });


    if(this.postId){
      this.$axios({
        url:'/post/'+this.postId,
        method:'get'
      }).then(res=>{
        const {data} =res.data
        let NEWcategories = []
        data.categories.forEach(e=>{
            NEWcategories.push(e.id)
        })
        data.categories=NEWcategories

        data.cover.forEach((e,index)=>{
          e.url=this.$url(e.url)
          e.uid=index
        })

         data.content =data.content.replace(/div/g,'p')
        this.form=data
      })
    }
  },
  methods: {

    onSubmit(){
      // 转换成api需要的格式
       const newArr = [];
      this.form.categories.forEach(e=>{
        newArr.push({id:e})
      })
      this.form.categories=newArr
      // console.log(this.form)

      this.$axios({
        url:this.postId?'/post_update/'+this.postId:'/post',
        method:'post',
        data:this.form
      }).then(res=>{
        const {data} = res.data
        // console.log(data);
      })

    },

    // 文件加到文本框内
    imgUpload(file, Editor, cursorLocation, resetUploader) {
      // file 使我们要上传的文件
      // Editor 是我们正在使用的编辑器
      // cursorLocation 这是子组件获取到的当前光标位置
      // restUploader 这是当你处理完了所有数据,应该重置这个上传的组件
      var formData = new FormData();
      formData.append("file", file);
      this.$axios({
        url: "/upload",
        method: "post",
        data: formData
      })
        .then(res => {
          const { data } = res.data;
          // 加上基准路径 跟 data的url
          let url = this.$axios.defaults.baseURL + data.url;

          // 这里是将我们传到服务器返回一个地址的图片放入编辑器当中
          Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
        })
        .catch(err => {
          const {data}=res.data
          // console.log(err);
        });
    },

    //封面缩略图
    handleRemove() {
        // console.log(file, fileList);
        // this.form.cover=fileList

         console.log("删除了图片");
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },

      Success(res){


        this.form.cover.push({
          id:res.data.id,

          url:this.$axios.defaults.baseURL+res.data.url
        })


      }

  }
};
</script>

<style>
</style>
